<?php


namespace app\api\controller;


use app\common\model\DeveloperException;
use app\common\model\LoginException;
use app\common\model\Users;
use think\App;
use think\exception\ValidateException;
use think\Validate;

class Base
{

    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;
    /**
     * 是否批量验证
     * @var bool
     */
    protected $batchValidate = false;

    protected $requestData;

    protected $responseData;

    /**
     * 构造方法
     * @access public
     * @param App $app 应用对象
     */
    public function __construct(App $app)
    {
        header('Access-Control-Allow-Origin:*');

        $this->app = $app;
        $this->request = $this->app->request;
        //解析请求体信息
        $this->parseData();


    }

    /**
     * 验证数据
     * @access protected
     * @param array $data 数据
     * @param string|array $validate 验证器名或者验证规则数组
     * @param array $message 提示信息
     * @param bool $batch 是否批量验证
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate(array $data, $validate, array $message = [], bool $batch = false)
    {
        if (is_array($validate)) {
            $v = new Validate();
            $v->rule($validate);
        } else {
            if (strpos($validate, '.')) {
                // 支持场景
                list($validate, $scene) = explode('.', $validate);
            }
            $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
            $v = new $class();
            if (!empty($scene)) {
                $v->scene($scene);
            }
        }

        $v->message($message);
        // 是否批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }

        $result = $v->failException(false)->check($data);
        if (true !== $result) {
            return $v->getError();
        } else {
            return $result;
        }
    }


    //获取用户信息
    protected function currentUser($bool = true)
    {
        $token = $this->requestData['token'];
        if (empty($token)) {
            if ($bool) {
                throw new LoginException('您还未登录');
            } else {
                $user = [];
            }
        } else {
            $user = Users::fromToken($token);
        }
        return $user;


    }

    protected function parseData()
    {
        $body = file_get_contents("php://input");
        if (!empty($body)) {
            if ($this->isEncrypt()) {
                //加密数据解密
                $this->requestData = aes_decrypt($body);
            } else {
                $this->requestData = json_decode($body, true);
            }
        }
    }

    //插入数据全部转为字符串
    private function encodeResponse(&$value)
    {
        if (is_scalar($value)) {
            $value = strval($value);
        } elseif (is_array($value)) {
            foreach ($value as $item) {
                $this->encodeResponse($item);
            }
        }
    }

    //插入结果报文
    protected function insertResponse($key, $value)
    {
        //将报文进行字符串编码(将null或数值转为字符串)
        $this->encodeResponse($value);
        if ($key) {
            $this->responseData["result_data"][$key] = $value;
        } else {
            $this->responseData["result_data"] = $value;
        }
    }

    //输出响应报文
    protected function response($info = "操作成功", $obj = 0)
    {
        //添加结果编码
        $this->responseData["result_code"] = "0000";
        //添加结果信息
        $this->responseData["result_info"] = $info;
        if (!isset($this->responseData['result_data'])) {
            if ($obj) {
                $this->responseData['result_data'] = new \stdClass();
            } else {
                $this->responseData['result_data'] = [];
            }
        }
        if ($this->isEncrypt()) {
            $data = aes_encrypt(json_encode($this->responseData));
            $data = ['body'=>$data];
        } else {
            $data = $this->responseData;
        }
        return json($data);
    }

    //是否加密
    private function isEncrypt()
    {
        if (input('get.no_encrypt') == 1) {
            return false;
        } else {
            return true;
        }

    }

    /**
     * 获取必选字段
     *
     * @param $param
     * @return mixed
     * @throws DeveloperException
     */
    protected function essentialParam($param)
    {
        if ($this->requestData && array_key_exists($param, $this->requestData)) {
            if ($this->requestData[$param] === "") {
                send_developer_error("必选字段【" . $param . "】不能为空！");
            }
            return $this->requestData[$param];
        } else {
            throw new DeveloperException("必选字段【" . $param . "】不存在,请核实文档后重试！");
        }
    }

    /**
     * 获取可选参数
     *
     * @param $param
     * @return string
     */
    protected function optionalParam($param)
    {
        if ($this->requestData && array_key_exists($param, $this->requestData)) {
            return $this->requestData[$param];
        } else {
            return "";
        }
    }


}